﻿using BacklogParser.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BacklogParser.Parsers
{
    public static class AgentParser
    {
        public static List<Agent> Parse(XElement parties)
        {
            var agents = parties.Descendants(Constants.Epo + "agents").ToList();
            return ParseAgents(agents);
        }

        private static List<Agent> ParseAgents(List<XElement> agentsElems)
        {
            var result = new List<Agent>();

            foreach (var agentsElem in agentsElems)
            {
                var agentElems = agentsElem.Descendants(Constants.Epo + "agent").ToList();
                var changeDateAttr = agentsElem.Attribute("change-date");
                var changeGazetteNum = agentsElem.Attribute("change-gazette-num");
                string changeDate = "";
                string changeGazette = "";

                if (changeDateAttr != null)
                    changeDate = changeDateAttr.Value;

                if (changeGazetteNum != null)
                    changeGazette = changeGazetteNum.Value;

                foreach (var agent in agentElems)
                {

                    var addresBookElement = agent.Descendants(Constants.Epo + "addressbook").First();
                    var addressBook = AddressBookParser.Parse(addresBookElement);
                    var parsedAgent = Agent.Create(addressBook);

                    string repType = "";
                    string sequence = "";
                    string cdsid = "";
                    var repTypeAttr = agent.Attribute("rep-type");
                    var sequeneAttr = agent.Attribute("sequence");
                    var cdsidAttr = addresBookElement.Attribute("cdsid");

                    if (repTypeAttr != null) repType = repTypeAttr.Value;

                    if (sequeneAttr != null) sequence = sequeneAttr.Value;
                    if (cdsidAttr != null) cdsid = cdsidAttr.Value;

                    parsedAgent.Sequence = sequence;
                    parsedAgent.RepType = repType;
                    parsedAgent.ChangeDate = changeDate;
                    parsedAgent.ChangeGazetteNum = changeGazette;
                    parsedAgent.CdsId = cdsid;

                    result.Add(parsedAgent);
                }
            }

            return result;
        }
    }
}
